<?php

namespace App\Http\Controllers\Api;

use App\ActivityBargain;
use App\ActivityBargainInitiate;
use App\ActivityBargainJoin;
use App\ActivityGroup;
use App\ActivityGroupAdd;
use App\ActivityGroupPrice;
use App\Coupons;
use App\Exceptions\OrderException;
use App\Express;
use App\Goods;
use App\GoodSpu;
use App\GoodsSnapshot;
use App\Http\Services\FileManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\OrderAddress;
use App\OrderItem;
use App\Orders;
use App\ShopCart;
use App\User;
use App\UserAddress;
use App\UserCoupon;
use App\UserInfo;
use App\UserIntegralRecord;
use Illuminate\Contracts\Encryption\EncryptException;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use phpDocumentor\Reflection\DocBlock\Tags\Uses;

class OrderController extends Controller{

    public function buildOrder(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        if(is_null($user->phone) || $user->phone == '')
            return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']);

        $goodsIds                      = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $num                           = !is_null($request->get('num')) && trim($request->get('num')) != "" ? $request->get('num') : 1;
        $type                          = !is_null($request->get('type')) && trim($request->get('type')) != "" ? $request->get('type') : 'goods';
        $addressId                     = !is_null($request->get('address_id')) ? $request->get('address_id') : 0;
/*        $isFreeShipping = $request->get('is_free_shipping');*/
      /*  $expressId      = !is_null($request->get('express_id')) ? $request->get('express_id') : 0;*/
        $couponId                      = !is_null($request->get('coupon_id')) ? $request->get('coupon_id') : 0;
        $remark                        = $request->get('remark');
        $goodSpuId                     = $request->get('good_spu_id');
        $activityId                    = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 0;
        $groupType                     = $request->get('group_type');
        $groupId                       = !is_null($request->get('group_id')) ? $request->get('group_id') : 0;





        // TODO 购物车购买
        if($type == 'shop_cart'){
            if(is_array($goodsIds)){
                $generateOrder = DB::transaction(function() use($user,$goodsIds,$addressId,$remark,$couponId){
                    $orderNum = ToolsManager::makeBillNum();
                    while(true){
                        $isOrders = Orders::whereOrderNum($orderNum)->first();
                        if($isOrders){
                            $orderNum = ToolsManager::makeBillNum();
                        }else{
                            break;
                        }
                    }


                    // Todo 记录订单地址
                    $userAddress=UserAddress::whereId($addressId)->whereUserId($user->id)->first();
                    if(!$userAddress)
                        throw new  OrderException(OrderException::AddressNotFound);

/*                    $newOrderAddress=self::generateOrderAddress($userAddress);*/

                    $newOrderAddress=new OrderAddress();
                    $newOrderAddress->consignee  = $userAddress->consignee;
                    $newOrderAddress->province   = $userAddress->province;
                    $newOrderAddress->city       = $userAddress->city;
                    $newOrderAddress->area       = $userAddress->area;
                    $newOrderAddress->address    = $userAddress->add_detail;
                    $newOrderAddress->postcode   = $userAddress->postcode;
                    $newOrderAddress->phone      = $userAddress->phone;
                    $newOrderAddress->telephone  = $userAddress->telephone;
                    $newOrderAddress->save();



                    $newOrder = new Orders();
                    $newOrder->user_id    = $user->id;
                    $newOrder->order_num  = $orderNum;
                    $newOrder->remark     = $remark;
                    $newOrder->address_id = $newOrderAddress->id;
                    $newOrder->save();

                    $amountSPrice    = 0;
                    $couponAmount    = 0;
                    $totalNum        = 0;
                    $isFreeShipping  = 0;
                    $i=0;
                  $goodsInfo = array();
                    foreach($goodsIds as $goodsId){

                        // ToDO 购物车记录
                        /** @var ShopCart $thisShopCart */
                        $thisShopCart = ShopCart::whereId($goodsId)->whereUserId($user->id)->first();

                        if(!$thisShopCart)
                            throw new OrderException(OrderException::ShopCartNotFound);
                        /** @var Goods $thisGoods */

                        $thisGoods = Goods::whereId($thisShopCart->goods_id)->whereIsShop(1)->first();
                        if(!$thisGoods)
                            throw new OrderException(OrderException::GoodsNotFound);

                        //ToDo 商品属性规格
                        $goodSpu=GoodSpu::whereId($thisShopCart->good_spu_id)->whereStatus(1)->first();
                        if(!$goodSpu)
                            throw  new OrderException(OrderException::GoodsNotFound);

                        //ToDo 库存

                        if($thisShopCart->num > $goodSpu->stock)
                            throw new OrderException(OrderException::GoodsStockNotFull."$thisGoods->name"."$goodSpu->spu_name");


                        //TODO  付款减库存
                   /*     $goodSpu->stock=$goodSpu->stock -$thisShopCart->num;
                        $goodSpu->save();*/

                        // ToDo 商品快照
                        $newGoodsSnapshot = new GoodsSnapshot();
                        $newGoodsSnapshot->goods_id               = $thisGoods->id;
                        $newGoodsSnapshot->ssn                    = $thisGoods->ssn;
                        $newGoodsSnapshot->name                   = $thisGoods->name.$goodSpu->spu_name;
                        $newGoodsSnapshot->m_price                = $thisGoods->m_price;
                        $newGoodsSnapshot->s_price                = $goodSpu->price;
                        $newGoodsSnapshot->thumb_id               = $thisGoods->thumb_id;
                        $newGoodsSnapshot->info                   = $thisGoods->info;
                        $newGoodsSnapshot->sale_count             = $thisGoods->sale_count;
                        $newGoodsSnapshot->type                   = $thisGoods->type;
                        $newGoodsSnapshot->exchange_integral      = $thisGoods->exchange_integral;
                        $newGoodsSnapshot->save();

                        array_push($goodsInfo,$newGoodsSnapshot);

                        //ToDo 包邮统计 0：不包邮   1：包邮
                        $isFreeShipping +=$thisGoods->is_free_shipping;
                        $i++;
                       /* $i=array_push($i,$thisGoods->is_free_shipping);*/

                        // ToDo 子订单

                        $newOrderItem = new OrderItem();
                        $newOrderItem->good_id            = $thisGoods->id;
                        $newOrderItem->order_id           = $newOrder->id;
                        $newOrderItem->item_num           = $newOrder->order_num . '#' . rand(1000,9999);
                        $newOrderItem->m_price            = $goodSpu->price;
                        $newOrderItem->s_price            = $goodSpu->price;
                        $newOrderItem->num                = $thisShopCart->num;
                        $newOrderItem->goods_snapshot_id  = $newGoodsSnapshot->id;
                        $newOrderItem->good_spu_id        = $goodSpu->id;
                        $newOrderItem->save();

                /*        $amountMPrice += (float)$newOrderItem->m_price * (int)$newOrderItem->num;*/
                        $amountSPrice += (float)$newOrderItem->s_price * (int)$newOrderItem->num;
                        $totalNum     += $newOrderItem->num;
                        $thisShopCart->delete();
                    }




                    /** 是否使用优惠券 $userCoupon */
               if($couponId !==0) {
                   /** @var UserCoupon $userCoupon */
                   $userCoupon = UserCoupon::whereId($couponId)->whereIsLocking(0)->whereIsUse(0)->whereUserId($user->id)->first();
                   if(!$userCoupon)
                       throw new OrderException(OrderException::UserCouponNotFound);

                   if(strtotime($userCoupon->end_time) < time())
                       throw  new OrderException(OrderException::CouponNotUse);
                   if($userCoupon->type == 'satisfy'){
                       if ($amountSPrice < $userCoupon->satisfy_money)
                           throw  new OrderException(OrderException::OrderAmountNotFull);
                   }

                   $couponAmount=$userCoupon->money;
                   $userCoupon->is_locking=1;
                   $userCoupon->save();
                   $newOrder->coupon_id=$userCoupon->id;
                   $newOrder->save();
               }



               //TODO 计算运费费用
               if($isFreeShipping==$i){
                   $expressFee=0;
                   $expressName="免运费";
               }else{
                   $express=Express::whereIsDefault(1)->first();
                   if(!$express)
                       throw new OrderException(OrderException::ExpressNotFound);
                   $expressFee=$express->fee;
                   $expressName=$express->name;
               }



                    $newOrder->m_amount    = $amountSPrice; /**   订单原价格 */
                    $newOrder->s_amount    = $amountSPrice - $couponAmount + (int)$expressFee; /**订单实付价格 */
                    $newOrder->status      = 1;
                    $newOrder->express     =$expressName;
                    $newOrder->save();

         /*          $newOrder=array([

                        "newOrder"=>$newOrder,
                        "order_address"=>$userAddress,
                        "order_couponAmount"=>$couponAmount,
                        "goodsInfo"=>$goodsInfo,

                    ]);*/


                    return $newOrder;
                });
            }else{
                return response()->json(['level' => 'error','message' => '数据格式错误']);
            }
        }elseif($type == 'goods'){
            // TODO 非购物车购买
            $generateOrder = DB::transaction(function() use($goodsIds,$user,$num,$addressId,$remark,$couponId,$goodSpuId){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($goodsIds)->whereIsShop(1)->first();
                if(!$thisGoods)
                    throw new OrderException(OrderException::GoodsNotFound);

                $orderNum = ToolsManager::makeBillNum();
                while(true){
                    $isOrders = Orders::whereOrderNum($orderNum)->first();
                    if($isOrders){
                        $orderNum = ToolsManager::makeBillNum();
                    }else{
                        break;
                    }
                }

                // Todo 记录订单地址
                $userAddress=UserAddress::whereId($addressId)->whereUserId($user->id)->first();
                if(!$userAddress)
                    throw new  OrderException(OrderException::AddressNotFound);
              /*  $newOrderAddress=self::generateOrderAddress($userAddress);*/

                $newOrderAddress=new OrderAddress();
                $newOrderAddress->consignee  = $userAddress->consignee;
                $newOrderAddress->province   = $userAddress->province;
                $newOrderAddress->city       = $userAddress->city;
                $newOrderAddress->area       = $userAddress->area;
                $newOrderAddress->address    = $userAddress->add_detail;
                $newOrderAddress->postcode   = $userAddress->postcode;
                $newOrderAddress->phone      = $userAddress->phone;
                $newOrderAddress->telephone  = $userAddress->telephone;
                $newOrderAddress->save();

                //TODO 生成订单
                $newOrder = new Orders();
                $newOrder->user_id     = $user->id;
                $newOrder->order_num   = $orderNum;
                $newOrder->type        = $thisGoods->type;
                $newOrder->remark      = $remark;
                $newOrder->address_id  = $newOrderAddress->id;
                $newOrder->save();

                  //TODO 生成子订单
                $newOrderItem = new OrderItem();
                $newOrderItem->good_id            = $thisGoods->id;
                $newOrderItem->order_id           = $newOrder->id;
                $newOrderItem->item_num           = $newOrder->order_num . '#' . rand(1000,9999);
                $newOrderItem->num                = $num;
                $newOrderItem->type               = $thisGoods->type;
                $newOrderItem->integral           = $thisGoods->exchange_integral*$num;
                $newOrderItem->save();



                $isFreeShipping=$thisGoods->is_free_shipping;


                $amountSPrice=round((float)$newOrderItem->s_price * (int)$newOrderItem->num,2);

                if($thisGoods->type=="common") {

                    //ToDo 商品属性规格
                    /** @var GoodSpu $goodSpu */
                    $goodSpu = GoodSpu::whereId($goodSpuId)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();

                    if (!$goodSpu)
                        throw  new OrderException(OrderException::GoodsNotFound);


                    //ToDo 库存
                    if($num > $goodSpu->stock)
                        throw new OrderException(OrderException::GoodsStockNotFull."$thisGoods->name"."$goodSpu->spu_name");

                    $newGoodsSnapshot=self::generateGoodsSnapshot($thisGoods,$goodSpu);

                    $newOrderItem->goods_snapshot_id  = $newGoodsSnapshot->id;
                    $newOrderItem->m_price            = $goodSpu->price;
                    $newOrderItem->s_price            = $goodSpu->price;
                    $newOrderItem->good_spu_id        = $goodSpu->id;
                    $newOrder->status       = 1;
                    $newOrderItem->save();

                    $amountSPrice=round((float)$newOrderItem->s_price * (int)$newOrderItem->num,2);

                }



                if($thisGoods->type=="integral") {

                    $newGoodsSnapshot = self::generateGoodsSnapshot($thisGoods);

                    $newOrder->status=1;
                    $newOrder->save();
                    $newOrderItem->goods_snapshot_id = $newGoodsSnapshot->id;
                    $newOrderItem->s_price=$thisGoods->s_price;
                    $newOrderItem->save();

                    $amountSPrice=round((float)$newOrderItem->s_price * (int)$newOrderItem->num,2);

                    //ToDo 库存
                    if($num > $thisGoods->stock)
                        throw new OrderException(OrderException::GoodsStockNotFull);


                    //TODO  付款减库存
                /*    $thisGoods->stock=$thisGoods->stock - $num;
                    $thisGoods->save();*/



            /*        $userIntegralRecords = UserIntegralRecord::whereUserId($user->id)->get();
                    $totalIntegral = 0;

                    if (count($userIntegralRecords) > 0) {
                        foreach ($userIntegralRecords as $userIntegralRecord) {
                            $totalIntegral += (int)$userIntegralRecord->integral;
                        }*/

                    $userInfo=UserInfo::whereUserId($user->id)->first();
                    if(!$userInfo)
                        throw new OrderException(OrderException::UserInfoNotFound);

                    if ($userInfo->integral< (int)$thisGoods->exchange_integral*(int)$num)

                        throw new OrderException(OrderException::IntegralNotFull);



                     /*   if ($totalIntegral < $thisGoods->exchange_integral * $num)
                            throw new OrderException(OrderException::IntegralNotFull);*/

                        /** @商品为积分商品&&商品包邮 */
                        if ( $isFreeShipping == 1) {
                            $thisGoods->stock=$thisGoods->stock - $num;
                            $newOrder->is_pay = 1;
                            $newOrder->status = 2;
                            $newOrder->integral= $thisGoods->exchange_integral * $num;
                            $newOrder->save();



                            $thisGoods->sale_count=$thisGoods->sale_count+$num;
                            $thisGoods->save();

                            // 积分记录

                            $userInfo->integral=(int)$userInfo->integral - (int)$thisGoods->exchange_integral*(int)$num;
                            $userInfo->save();

                            $newUserIntegralRecord = new UserIntegralRecord();

                            $newUserIntegralRecord->num=$num;
                            $newUserIntegralRecord->integral = -($thisGoods->exchange_integral * $num);
                            $newUserIntegralRecord->order_num = $newOrder->order_num;
                            $newUserIntegralRecord->user_id = $user->id;
                            $newUserIntegralRecord->type = $thisGoods->type;
                            $newUserIntegralRecord->goods_name = $thisGoods->name;
                            $newUserIntegralRecord->save();

                        }


                  /*  } else {
                        throw new OrderException(OrderException::IntegralNotRecord);
                    }*/
                }

                $newOrder->integral    =$thisGoods->exchange_integral*$newOrderItem->num;
                $couponAmount=0;


                /** 是否使用优惠券 $userCoupon */
                if($couponId !==0) {
                    /** @var UserCoupon $userCoupon */
                    $userCoupon = UserCoupon::whereId($couponId)->whereIsUse(0)->whereUserId($user->id)->first();
                    if(!$userCoupon)
                        throw new OrderException(OrderException::UserCouponNotFound);

                    if(strtotime($userCoupon->end_time) < time())
                        throw  new OrderException(OrderException::CouponNotUse);

                    if($userCoupon == 'satisfy'){
                        if ($amountSPrice < $userCoupon->satisfy_money)
                            throw  new OrderException(OrderException::OrderAmountNotFull);
                    }


                    $couponAmount       =  $userCoupon->money;
                    $userCoupon->is_locking=1;
                    $userCoupon->save();
                    $newOrder->coupon_id=$userCoupon->id;
                    $newOrder->save();
                }


                /** 是否包邮 */
                if($isFreeShipping==1){
                    $expressFee=0;
                    $expressName="免运费";
                }else{
                    $express=Express::whereIsDefault(1)->first();
                    if(!$express)
                        throw new OrderException(OrderException::ExpressNotFound);

                    $expressFee   =  $express->fee;
                    $expressName  =  $express->name;
                }


                $newOrder->m_amount     =  $amountSPrice;  /**@订单原价格*/
                $newOrder->s_amount     =  $amountSPrice + $expressFee - $couponAmount; /**@订单实付价格*/
                $newOrder->express_fee  =  $expressFee;
                $newOrder->express      =  $expressName;
                $newOrder->save();

             /*   $newOrder=array([

                    "newOrder"=>$newOrder,
                    "order_address"=>$userAddress,
                    "order_couponAmount"=>$couponAmount,
                    "order_goods"=>$newGoodsSnapshot,

                ]);*/



                return $newOrder;



            });
        }elseIf($type == 'bargain'){
            $generateOrder = DB::transaction(function() use($goodsIds,$user,$num,$addressId,$remark,$couponId,$goodSpuId,$activityId) {
                /** @var ActivityBargainInitiate $thisActivityBargainInitiate */
                $thisActivityBargainInitiate = ActivityBargainInitiate::whereId($activityId)->first();
                if(!$thisActivityBargainInitiate)
                    throw new OrderException(OrderException::ActivityNotFound);

                if(strtotime($thisActivityBargainInitiate->end_time) <= time())
                    throw new OrderException(OrderException::ActivityExpired);

                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($thisActivityBargainInitiate->goods_id)->whereIsShop(1)->first();
                if(!$thisGoods)
                    throw new OrderException(OrderException::GoodsNotFound);

                //ToDo 商品属性规格
                /** @var GoodSpu $goodSpu */
                $goodSpu = GoodSpu::whereId($thisActivityBargainInitiate->goods_spu_id)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
                if (!$goodSpu)
                    throw  new OrderException(OrderException::GoodsNotFound);


                //ToDo 库存
                if( $goodSpu->stock < $num)
                    throw new OrderException(OrderException::GoodsStockNotFull."$thisGoods->name"."$goodSpu->spu_name");

                $orderNum = ToolsManager::makeBillNum();
                while(true){
                    $isOrders = Orders::whereOrderNum($orderNum)->first();
                    if($isOrders){
                        $orderNum = ToolsManager::makeBillNum();
                    }else{
                        break;
                    }
                }

                // Todo 记录订单地址
                /** @var UserAddress $userAddress */
                $userAddress=UserAddress::whereId($addressId)->whereUserId($user->id)->first();
                if(!$userAddress)
                    throw new  OrderException(OrderException::AddressNotFound);
                /*  $newOrderAddress=self::generateOrderAddress($userAddress);*/

                $newOrderAddress=new OrderAddress();
                $newOrderAddress->consignee  = $userAddress->consignee;
                $newOrderAddress->province   = $userAddress->province;
                $newOrderAddress->city       = $userAddress->city;
                $newOrderAddress->area       = $userAddress->area;
                $newOrderAddress->address    = $userAddress->add_detail;
                $newOrderAddress->postcode   = $userAddress->postcode;
                $newOrderAddress->phone      = $userAddress->phone;
                $newOrderAddress->telephone  = $userAddress->telephone;
                $newOrderAddress->save();


                //TODO 生成订单
                $newOrder = new Orders();
                $newOrder->user_id     = $user->id;
                $newOrder->order_num   = $orderNum;
                $newOrder->type        = 'bargain';
                $newOrder->remark      = $remark;
                $newOrder->address_id  = $newOrderAddress->id;
                $newOrder->status       = 1;
                $newOrder->activity_id  = $thisActivityBargainInitiate->id;
                $newOrder->save();

                $newGoodsSnapshot=self::generateGoodsSnapshot($thisGoods,$goodSpu);

                //TODO 生成子订单
                $newOrderItem = new OrderItem();
                $newOrderItem->good_id            = $thisGoods->id;
                $newOrderItem->order_id           = $newOrder->id;
                $newOrderItem->item_num           = $newOrder->order_num . '#' . rand(1000,9999);
                $newOrderItem->goods_snapshot_id  = $newGoodsSnapshot->id;
                $newOrderItem->num                = $num;
                $newOrderItem->type               = $thisGoods->type;
                $newOrderItem->m_price            = $goodSpu->price;
                $newOrderItem->s_price            = $thisActivityBargainInitiate->finally_money;
                $newOrderItem->good_spu_id        = $goodSpu->id;
                $newOrderItem->save();

                $amountSPrice=round((float)$newOrderItem->s_price * (int)$newOrderItem->num,2);

                /** 是否包邮 */
                if($thisGoods->is_free_shipping==1){
                    $expressFee=0;
                    $expressName="免运费";
                }else{
                    $express=Express::whereIsDefault(1)->first();
                    if(!$express)
                        throw new OrderException(OrderException::ExpressNotFound);

                    $expressFee   =  $express->fee;
                    $expressName  =  $express->name;
                }

                $newOrder->m_amount     =  $amountSPrice;  /**@订单原价格*/
                $newOrder->s_amount     =  $amountSPrice + $expressFee; /**@订单实付价格*/
                $newOrder->express_fee  =  $expressFee;
                $newOrder->express      =  $expressName;
                $newOrder->save();

                $thisActivityBargainInitiate->order_num = $newOrder->order_num;
                $thisActivityBargainInitiate->save();

                return $newOrder;
            });
        }elseif($type == 'group'){
            $generateOrder = DB::transaction(function() use($goodsIds,$user,$num,$addressId,$remark,$couponId,$goodSpuId,$activityId,$groupType,$groupId) {
                /** @var ActivityGroup $thisActivityGroup */
                $thisActivityGroup = ActivityGroup::whereId($activityId)->whereStatus(1)->first();
                if(!$thisActivityGroup)
                    throw new OrderException(OrderException::ActivityNotFound);

                if(strtotime($thisActivityGroup->end_time) <= time())
                    throw new OrderException(OrderException::ActivityExpired);

                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($thisActivityGroup->goods_id)->whereIsShop(1)->first();
                if(!$thisGoods)
                    throw new OrderException(OrderException::GoodsNotFound);

                //ToDo 商品属性规格
                /** @var GoodSpu $goodSpu */
                $goodSpu = GoodSpu::whereId($goodSpuId)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
                if (!$goodSpu)
                    throw  new OrderException(OrderException::GoodsNotFound);

                if(!is_null($groupType) && $groupType != ''){
                    if($groupType == 'alone'){
                        $thisGroupType = 1;

                        //TODO 正常价
                        $goodsPrice = $goodSpu->price;
                        $groupId    = 0;
                    }elseif($groupType == 'initiate'){
                        $thisGroupType = 2;

                        //TODO 拼团价
                        /** @var ActivityGroupPrice $activityGroupPrice */
                        $activityGroupPrice = ActivityGroupPrice::whereActivityGroupId($thisActivityGroup->id)->whereGoodsId($thisGoods->id)->whereGoodsSpuId($goodSpu->id)->first();
                        if($activityGroupPrice){
                            $goodsPrice = $activityGroupPrice->many_price;
                        }else{
                            $goodsPrice = $goodSpu->price;
                        }

                        $groupId    = 0;
                    }elseif($groupType == 'part'){
                        $thisGroupType = 3;

                        //TODO 拼团价
                        /** @var ActivityGroupPrice $activityGroupPrice */
                        $activityGroupPrice = ActivityGroupPrice::whereActivityGroupId($thisActivityGroup->id)->whereGoodsId($thisGoods->id)->whereGoodsSpuId($goodSpu->id)->first();
                        if($activityGroupPrice){
                            $goodsPrice = $activityGroupPrice->many_price;
                        }else{
                            $goodsPrice = $goodSpu->price;
                        }

                        /** @var ActivityGroupAdd $activityGroupAdd */
                        $activityGroupAdd = ActivityGroupAdd::whereId($groupId)->first();
                        if(!$activityGroupAdd)
                            throw new OrderException(OrderException::GroupNotFound);

                        if($thisActivityGroup->max_group_num <= $activityGroupAdd->group_num)
                            throw new OrderException(OrderException::GroupNotFound);

                        if (strtotime($activityGroupAdd->end_time) <= time())
                            throw new OrderException(OrderException::GroupAlreadyEnd);

                        if($activityGroupAdd->status != 0)
                            throw new OrderException(OrderException::GroupNumEnd);

                        $groupId    = $activityGroupAdd->id;
                    }else{
                        throw new OrderException(OrderException::SystemError);
                    }
                }else{
                    throw new OrderException(OrderException::SystemError);
                }

                //ToDo 库存
                if( $goodSpu->stock < $num)
                    throw new OrderException(OrderException::GoodsStockNotFull."$thisGoods->name"."$goodSpu->spu_name");

                $orderNum = ToolsManager::makeBillNum();
                while(true){
                    $isOrders = Orders::whereOrderNum($orderNum)->first();
                    if($isOrders){
                        $orderNum = ToolsManager::makeBillNum();
                    }else{
                        break;
                    }
                }

                // Todo 记录订单地址
                /** @var UserAddress $userAddress */
                $userAddress=UserAddress::whereId($addressId)->whereUserId($user->id)->first();
                if(!$userAddress)
                    throw new  OrderException(OrderException::AddressNotFound);
                /*  $newOrderAddress=self::generateOrderAddress($userAddress);*/

                $newOrderAddress=new OrderAddress();
                $newOrderAddress->consignee  = $userAddress->consignee;
                $newOrderAddress->province   = $userAddress->province;
                $newOrderAddress->city       = $userAddress->city;
                $newOrderAddress->area       = $userAddress->area;
                $newOrderAddress->address    = $userAddress->add_detail;
                $newOrderAddress->postcode   = $userAddress->postcode;
                $newOrderAddress->phone      = $userAddress->phone;
                $newOrderAddress->telephone  = $userAddress->telephone;
                $newOrderAddress->save();

                //TODO 生成订单
                $newOrder = new Orders();
                $newOrder->user_id      = $user->id;
                $newOrder->order_num    = $orderNum;
                $newOrder->type         = 'group';
                $newOrder->remark       = $remark;
                $newOrder->group_type   = $thisGroupType;
                $newOrder->group_id     = $groupId;
                $newOrder->address_id   = $newOrderAddress->id;
                $newOrder->status       = 1;
                $newOrder->activity_id  = $thisActivityGroup->id;
                $newOrder->save();

                $newGoodsSnapshot=self::generateGoodsSnapshot($thisGoods,$goodSpu);

                //TODO 生成子订单
                $newOrderItem = new OrderItem();
                $newOrderItem->good_id            = $thisGoods->id;
                $newOrderItem->order_id           = $newOrder->id;
                $newOrderItem->item_num           = $newOrder->order_num . '#' . rand(1000,9999);
                $newOrderItem->goods_snapshot_id  = $newGoodsSnapshot->id;
                $newOrderItem->num                = $num;
                $newOrderItem->type               = $thisGoods->type;
                $newOrderItem->m_price            = $goodSpu->price;
                $newOrderItem->s_price            = $goodsPrice;
                $newOrderItem->good_spu_id        = $goodSpu->id;
                $newOrderItem->save();

                $amountSPrice=round((float)$newOrderItem->s_price * (int)$newOrderItem->num,2);

                /** 是否包邮 */
                if($thisGoods->is_free_shipping==1){
                    $expressFee=0;
                    $expressName="免运费";
                }else{
                    $express=Express::whereIsDefault(1)->first();
                    if(!$express)
                        throw new OrderException(OrderException::ExpressNotFound);

                    $expressFee   =  $express->fee;
                    $expressName  =  $express->name;
                }

                $newOrder->m_amount     =  $amountSPrice;  /**@订单原价格*/
                $newOrder->s_amount     =  $amountSPrice + $expressFee; /**@订单实付价格*/
                $newOrder->express_fee  =  $expressFee;
                $newOrder->express      =  $expressName;
                $newOrder->save();

                return $newOrder;
            });
        }else{
            return response()->json(['level' => 'error','message' => '订单类型不正确']);
        }

        return response()->json(['level' => 'success','message' => '订单生成成功','data' => $generateOrder]);
    }

    public function getOrders(Request $request){
        $orderNum = $request->get('order_num');

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereOrderNum($orderNum)->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if($thisOrder->status == 1 && (strtotime($thisOrder->created_at) + (30 * 60)) < time()){
            $thisOrder->status = 6;
            $thisOrder->save();

            /** @var UserCoupon $thisCoupon */
            $thisCoupon = UserCoupon::whereId($thisOrder->coupon_id)->first();
            if($thisCoupon){
                $thisCoupon->is_locking = 0;
                $thisCoupon->save();
            }
        }

        if($thisOrder->type == 'bargain'){
            /** @var ActivityBargainInitiate $activityBargainInitiate */
            $activityBargainInitiate = ActivityBargainInitiate::whereId($thisOrder->activity_id)->first();
            if($activityBargainInitiate){
                /** @var ActivityBargain $activityBargain */
                $activityBargain = ActivityBargain::whereId($activityBargainInitiate->ab_id)->first();
                if($activityBargain){
                    $thisOrder->bargain_id       = $activityBargain->id;
                }
            }
        }

        $orderAddress=OrderAddress::whereId($thisOrder->address_id)->first();
        /** @var OrderItem $orderItem */
        $orderItems = OrderItem::whereOrderId($thisOrder->id)->get();
        if(count($orderItems) > 0){
            foreach($orderItems as $orderItem){
                /** @var Goods $thisGoods */
                $thisGoods = GoodsSnapshot::whereId($orderItem->goods_snapshot_id)->first();
                if($thisGoods){
                    $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                }

                $thisGoodsSpu = GoodSpu::whereId($orderItem->good_spu_id)->whereGoodsId($orderItem->good_id)->first();

                $orderItem->goods_info     = $thisGoods;
                $orderItem->goods_spu_info = $thisGoodsSpu;
            }
        }

        $thisCoupon = UserCoupon::whereId($thisOrder->coupon_id)->first();

        $thisOrder->order_item       = $orderItems;
        $thisOrder->order_address    = $orderAddress;
        $thisOrder->user_coupon_info = $thisCoupon;
        $thisOrder->amount           = $thisOrder->s_amount;

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisOrder]);
    }

    public function getUserAllOrders(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        if(is_null($user->phone) || $user->phone == '')
            return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']);

        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 0;
        $status = !is_null($request->get('status')) ? $request->get('status') : 0;

        /** @var Orders $allOrder*/
        if($status != '' && $status != 0){
            $allOrders = Orders::whereUserId($user->id)->whereStatus($status)->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        }else{
            $allOrders = Orders::whereUserId($user->id)->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        }

        if(count($allOrders) > 0){
            foreach($allOrders as $allOrder){
                if($allOrder->status == 1 && (strtotime($allOrder->created_at) + (30 * 60)) < time()){
                    $allOrder->status = 6;
                    $allOrder->save();

                    /** @var UserCoupon $thisCoupon */
                    $thisCoupon = UserCoupon::whereId($allOrder->coupon_id)->first();
                    if($thisCoupon){
                        $thisCoupon->is_locking = 0;
                        $thisCoupon->save();
                    }
                }
                /** @var OrderItem $orderItem */
                if($allOrder->status == 4){
                    $orderItems = OrderItem::whereOrderId($allOrder->id)->whereStatus(0)->get();
                }else{
                    $orderItems = OrderItem::whereOrderId($allOrder->id)->get();
                }

                if(count($orderItems) > 0){
                    foreach($orderItems as $orderItem){
                        /** @var GoodsSnapshot $thisGoods */
/*                        $thisGoods = Goods::whereId($orderItem->good_id)->first();*/
                        $thisGoods = GoodsSnapshot::whereGoodsId($orderItem->good_id)->first();
                        if($thisGoods){
                            $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                        }

                        $thisGoodsSpu = GoodSpu::whereId($orderItem->good_spu_id)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
                        if($thisGoodsSpu){

                            $orderItem->goods_spu_info = $thisGoodsSpu;

                        }
                        $orderItem->goods_info     = $thisGoods;
                    }
                }

                if($allOrder->type == 'bargain'){
                    /** @var ActivityBargainInitiate $activityBargainInitiate */
                    $activityBargainInitiate = ActivityBargainInitiate::whereId($allOrder->activity_id)->first();
                    if($activityBargainInitiate){
                        /** @var ActivityBargain $activityBargain */
                        $activityBargain = ActivityBargain::whereId($activityBargainInitiate->ab_id)->first();
                        if($activityBargain){
                            $allOrder->bargain_id       = $activityBargain->id;
                        }
                    }
                }

                if($allOrder->status == 1){
                    $allOrder->statusType = '待付款';
                }elseif($allOrder->status == 2){
                    $allOrder->statusType = '待发货';
                }elseif($allOrder->status == 3){
                    $allOrder->statusType = '待收货';
                }elseif($allOrder->status == 4){
                    $allOrder->statusType = '待评价';
                }elseif($allOrder->status == 6){
                    $allOrder->statusType = '已取消';
                }elseif($allOrder->status == 8){
                    $allOrder->statusType = '待分享';
                }

                $allOrder->order_item = $orderItems;



            }
        }

        $orderNumber     = Orders::whereUserId($user->id)->count();
        $PendingPayment  = Orders::whereUserId($user->id)->whereStatus(1)->count();
        $toBeDelivered   = Orders::whereUserId($user->id)->whereStatus(2)->count();
        $PendingReceipt  = Orders::whereUserId($user->id)->whereStatus(3)->count();
        $WaitComment     = Orders::whereUserId($user->id)->whereStatus(4)->count();
        $pendingSharing  = Orders::whereUserId($user->id)->whereStatus(8)->count();


        return response()->json([
            'level' => 'success',
            'message' => '获取成功',
            'data' => $allOrders,
            'order_number' => $orderNumber,
            'Pending_payment' => $PendingPayment,
            'to_be_delivered' => $toBeDelivered,
            'Pending_receipt' => $PendingReceipt,
            'Wait_comment'    => $WaitComment,
            'pending_sharing' => $pendingSharing
        ]);
    }

    public function cancelOrder(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        if(is_null($user->phone) || $user->phone == '')
            return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']);

        $orderNum = !is_null($request->get('order_num')) ? $request->get('order_num') : '';

        /** @var Orders $orders */
        $orders = Orders::whereOrderNum($orderNum)->whereUserId($user->id)->first();
        if(!$orders || ($orders && $orders->status == 6))
            return response()->json(['level' => 'error','message' => '该订单不存在或已取消']);

        $orders->status = 6;
        $orders->save();

        /** @var UserCoupon $thisCoupon */
        $thisCoupon = UserCoupon::whereId($orders->coupon_id)->first();
        if($thisCoupon){
            $thisCoupon->is_locking = 0;
            $thisCoupon->save();
        }

        return response()->json(['level' => 'success','message' => '订单取消成功','data' => $orders]);
    }

    /**
     * 使用优惠券
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function useCoupon(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $couponId    = !is_null($request->get('coupon_id')) ? $request->get('coupon_id') : 0;
        $goodsId     = $request->get('goods_id');
        $num         = $request->get('num');
        $goodsSpuId  = !is_null($request->get('goods_spu_id')) ? $request->get('goods_spu_id') : 0;
        $type        = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'goods';

        /** @var UserCoupon $thisUserCoupon */
        $thisUserCoupon = UserCoupon::whereCouponId($couponId)->whereUserId($user->id)->first();
        if(!$thisUserCoupon)
            return response()->json(['level' => 'error','message' => '您没有该优惠券!']);

        if($thisUserCoupon->is_use == 1)
            return response()->json(['level' => 'error','message' => '该优惠券已使用']);

        if(strtotime($thisUserCoupon->cutoff_time) >= time())
            return response()->json(['level' => 'error','message' => '该优惠券已过期']);

        if($thisUserCoupon->is_locking == 1)
            return response()->json(['level' => 'error','message' => '优惠券已被锁定']);

        if($type == 'goods'){
            /** @var Goods $thisGoods */
            $thisGoods = Goods::whereId($goodsId)->whereIsShop(1)->first();
            if(!$thisGoods)
                return response()->json(['level' => 'error','message' => '该商品已下架']);

            /** @var GoodSpu $thisGoodsSpu */
            $thisGoodsSpu = GoodSpu::whereId($goodsSpuId)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
            if(!$thisGoodsSpu)
                return response()->json(['level' => 'error','message' => '商品属性不存在']);

            if($thisGoodsSpu->stock < $num || $thisGoodsSpu->stock == 0)
                return response()->json(['level' => 'error','message' => '商品库存不足']);

            /** @var Express $express */
            $express = Express::whereIsDefault(1)->first();
            if(!$express)
                return response()->json(['level' => 'error','message' => '未找到快递公司']);

            if($thisUserCoupon->type == 'direct'){
                $goodsMoneyTotal = round((float)$thisGoodsSpu->price * (int)$num - (float)$thisUserCoupon->money,2);
            }else{
                if($thisUserCoupon->satisfy_money > round((float)$thisGoodsSpu->price * (int)$num,2))
                    return response()->json(['level' => 'error','message' => '未达到优惠券使用要求']);

                $goodsMoneyTotal = round((float)$thisGoodsSpu->price * (int)$num - (float)$thisUserCoupon->money,2);
            }

            if($thisGoods->is_free_shipping == 1){
                $goodsMoney = $goodsMoneyTotal;
            }else{
                $goodsMoney = (float)$goodsMoneyTotal + (float)$express->fee;
            }


        }else{
            if(!is_array($goodsId))
                return response()->json(['level' => 'error','message' => '数据格式错误！']);

            $goodsMoneyTotal = 0;
            $goodsNum = count($goodsId);
            $isFreeShipping = 0;

            if(count($goodsId) > 0){
                foreach($goodsId as $goodId){
                    /** @var Goods $thisGoods */
                    $thisGoods = Goods::whereId($goodId['good_id'])->whereIsShop(1)->first();
                    if(!$thisGoods)
                        return response()->json(['level' => 'error','message' => '商品已下架,请重新下单']);

                    /** @var GoodSpu $thisGoodsSpu */
                    $thisGoodsSpu = GoodSpu::whereId($goodId['goods_spu_id'])->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
                    if(!$thisGoodsSpu)
                        return response()->json(['level' => 'error','message' => '商品属性不存在，请重新下单']);

                    if($thisGoods->is_free_shipping ==1)
                        $isFreeShipping += 1;

                    $goodsMoneyTotal += round((float)$thisGoodsSpu->price * (int)$goodId['num'],2);
                }
            }

            /** @var Express $express */
            $express = Express::whereIsDefault(1)->first();
            if(!$express)
                return response()->json(['level' => 'error','message' => '未找到快递公司']);

            if($thisUserCoupon->type == 'direct'){
                if($goodsNum == $isFreeShipping){
                    $goodsMoney = (float)$goodsMoneyTotal - (float)$thisUserCoupon->money;
                }else{
                    $goodsMoney = round((float)$goodsMoneyTotal - (float)$thisUserCoupon->money + (float)$express->fee,2);
                }
            }else{
                if($thisUserCoupon->satisfy_money > $goodsMoneyTotal)
                    return response()->json(['level' => 'error','message' => '未达到优惠券使用要求']);

                if($goodsNum == $isFreeShipping){
                    $goodsMoney = (float)$goodsMoneyTotal - (float)$thisUserCoupon->money;
                }else{
                    $goodsMoney = round((float)$goodsMoneyTotal - (float)$thisUserCoupon->money + (float)$express->fee,2);
                }
            }
        }

        $result['coupon_money'] = $thisUserCoupon->money;
        $result['goods_money'] = $goodsMoney >= 0 ? $goodsMoney : 0.00;

        return response()->json(['level' => 'success','message' => '优惠成功','data' => $result]);
    }

    public static function generateGoodsSnapshot(Goods $thisGoods,GoodSpu $thisGoodsSpu = null){
        $newGoodsSnapshot = new GoodsSnapshot();
        $newGoodsSnapshot->goods_id               = $thisGoods->id;
        $newGoodsSnapshot->ssn                    = $thisGoods->ssn;
        $newGoodsSnapshot->name                   = $thisGoods->name;
        if(!is_null($thisGoodsSpu)){
            $newGoodsSnapshot->goods_spu_name         = $thisGoodsSpu->spu_name;
        }
        $newGoodsSnapshot->m_price                = $thisGoods->m_price;
        $newGoodsSnapshot->s_price                = $thisGoods->s_price;
        $newGoodsSnapshot->thumb_id               = $thisGoods->thumb_id;
        $newGoodsSnapshot->integral               = $thisGoods->integral;
        $newGoodsSnapshot->info                   = $thisGoods->info;
        $newGoodsSnapshot->sale_count             = $thisGoods->sale_count;
        $newGoodsSnapshot->type                   = $thisGoods->type;
        $newGoodsSnapshot->exchange_integral      = $thisGoods->exchange_integral;
        $newGoodsSnapshot->save();
        return $newGoodsSnapshot;
    }

    public  static  function generateOrderAddress(UserAddress $userAddress){


        $newOrderAddress=new OrderAddress();
        $newOrderAddress->consignee  = $userAddress->consignee;
        $newOrderAddress->province   = $userAddress->province;
        $newOrderAddress->city       = $userAddress->city;
        $newOrderAddress->area       = $userAddress->area;
        $newOrderAddress->address    = $userAddress->add_detail;
        $newOrderAddress->postcode   = $userAddress->postcode;
        $newOrderAddress->phone      = $userAddress->phone;
        $newOrderAddress->telephone  = $userAddress->telephone;
        $newOrderAddress->save();


    }

    public function submitOrder(Request $request){
        $goodsIds   = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $num        = !is_null($request->get('num')) && trim($request->get('num')) != "" ? $request->get('num') : 1;
        $type       = !is_null($request->get('type')) && trim($request->get('type')) != "" ? $request->get('type') : 'goods';
        $goodsSpuId = !is_null($request->get('goods_spu_id')) && $request->get('goods_spu_id') != '' ? $request->get('goods_spu_id') : 0;
        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 0;
        $groupType  = $request->get('group_type');
        $groupId    = !is_null($request->get('group_id')) ? $request->get('group_id') : 0;

        if($type == 'goods'){
            /** @var Goods $thisGoods */
            $thisGoods = Goods::whereId($goodsIds)->whereIsShop(1)->first();
            if(!$thisGoods)
                return response()->json(['level' => 'error','message' => '该商品已下架']);

            if($thisGoods->type == 'common'){
                /** @var GoodSpu $thisGoodsSpu */
                $thisGoodsSpu = GoodSpu::whereId($goodsSpuId)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
                if(!$thisGoodsSpu)
                    return response()->json(['level' => 'error','message' => '商品属性不存在']);

                if($thisGoodsSpu->stock < $num || $thisGoodsSpu->stock == 0)
                    return response()->json(['level' => 'error','message' => '商品库存不足']);

                /** @var Express $express */
                $express = Express::whereIsDefault(1)->first();
                if(!$express)
                    return response()->json(['level' => 'error','message' => '未找到快递公司']);

                if($thisGoods->is_free_shipping == 1){
                    $goodsTotalAmount = round((float)$thisGoodsSpu->price * (int)$num,2);
                }else{
                    $goodsTotalAmount = round((float)$thisGoodsSpu->price * (int)$num + (float)$express->fee,2);
                }

                $thisGoods->goods_spu_info = $thisGoodsSpu;

            }elseif($thisGoods->type == 'integral'){
                if($thisGoods->stock < $num || $thisGoods->stock == 0)
                    return response()->json(['level' => 'error','message' => '商品库存不足']);

                /** @var Express $express */
                $express = Express::whereIsDefault(1)->first();
                if(!$express)
                    return response()->json(['level' => 'error','message' => '未找到快递公司']);

                if($thisGoods->is_free_shipping == 1){
                    $goodsTotalAmount = round((float)$thisGoods->s_price * (int)$num,2);
                }else{
                    $goodsTotalAmount = round((float)$thisGoods->s_price * (int)$num + (float)$express->fee,2);
                }
            }else{
                return response()->json(['level' => 'error','message' => '系统错误']);
            }

            $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
            $thisGoods->goods_num = $num;


            $result['goods_info']         = [$thisGoods];
            $result['express_company']    = $express->name;
            if($thisGoods->is_free_shipping == 1){
                $result['express_fee']    = 0;
            }else{
                $result['express_fee']    = $express->fee;
            }
            $result['goods_total_amount'] = $goodsTotalAmount;
        }elseif($type == 'shop_cart'){
            if(is_array($goodsIds)){
                $goodsInfoArr = array();
                $goodsTotalAmount = 0;
                $goodsNum = count($goodsIds);
                $isFreeShipping = 0;
                if(count($goodsIds) > 0){
                    foreach($goodsIds as $goodsId){
                        /** @var ShopCart $shopCart */
                        $shopCart = ShopCart::whereId($goodsId)->first();
                        if(!$shopCart)
                            return response()->json(['level' => 'error','message' => '该购物车商品不存在']);

                        /** @var Goods $thisGoods */
                        $thisGoods = Goods::whereId($shopCart->goods_id)->whereIsShop(1)->first();
                        if(!$thisGoods)
                            return response()->json(['level' => 'error','message' => '商品已下架']);

                        /** @var GoodSpu $thisGoodsSpu */
                        $thisGoodsSpu = GoodSpu::whereId($shopCart->good_spu_id)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
                        if(!$thisGoodsSpu)
                            return response()->json(['level' => 'error','message' => '商品属性不存在']);

                        $thisGoods->thumb_url      = FileManager::getImgUrl($thisGoods->thumb_id);
                        $thisGoods->goods_num      = $shopCart->num;
                        $thisGoods->goods_spu_info = $thisGoodsSpu;

                        if($thisGoods->is_free_shipping == 1)
                            $isFreeShipping += 1;

                        $goodsTotalAmount += round((float)$thisGoodsSpu->price * (int)$shopCart->num,2);
                        array_push($goodsInfoArr,$thisGoods);

                    }
                }

                /** @var Express $express */
                $express = Express::whereIsDefault(1)->first();
                if(!$express)
                    return response()->json(['level' => 'error','message' => '未找到快递公司']);

                $result['goods_info']         = $goodsInfoArr;
                $result['express_company']    = $express->name;
                if($goodsNum == $isFreeShipping){
                    $result['express_fee']    = 0;
                }else{
                    $result['express_fee']    = $express->fee;
                }
                if($goodsNum == $isFreeShipping){
                    $result['goods_total_amount'] = $goodsTotalAmount;
                }else{
                    $result['goods_total_amount'] = round((float)$goodsTotalAmount + (float)$express->fee,2);
                }
                $result['shop_cart'] = $goodsIds;
            }else{
                return response()->json(['level' => 'error','message' => '数据格式不正确','data' => $goodsIds]);
            }
        }elseIf($type == 'bargain'){
            /** @var ActivityBargainInitiate $thisActivityBargainInitiate */
            $thisActivityBargainInitiate = ActivityBargainInitiate::whereId($activityId)->first();
            if(!$thisActivityBargainInitiate)
                return response()->json(['level' => 'error','message' => '未找到该活动']);

            if(strtotime($thisActivityBargainInitiate->end_time) <= time())
                return response()->json(['level' => 'error','message' => '活动已过期，请参与其他活动']);

            /** @var Goods $thisGoods */
            $thisGoods = Goods::whereId($thisActivityBargainInitiate->goods_id)->whereIsShop(1)->first();
            if(!$thisGoods)
                return response()->json(['level' => 'error','message' => '该商品不存在']);

            //ToDo 商品属性规格
            /** @var GoodSpu $goodSpu */
            $goodSpu = GoodSpu::whereId($thisActivityBargainInitiate->goods_spu_id)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
            if (!$goodSpu)
                return response()->json(['level' => 'error','message' => '该属性的商品不存在']);


            //ToDo 库存
            if( $goodSpu->stock < $num)
                return response()->json(['level' => 'error','message' => '商品库存不足']);

            $thisGoods->goods_spu_info = $goodSpu;


            /** @var Express $express */
            $express = Express::whereIsDefault(1)->first();
            if(!$express)
                return response()->json(['level' => 'error','message' => '未找到快递公司']);

            if($thisGoods->is_free_shipping == 1){
                $goodsTotalAmount = round((float)$thisActivityBargainInitiate->finally_money * (int)$num,2);
            }else{
                $goodsTotalAmount = round((float)$thisActivityBargainInitiate->finally_money * (int)$num + (float)$express->fee,2);
            }

            $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
            $thisGoods->goods_num = $num;


            $result['goods_info']         = [$thisGoods];
            $result['activity_info']        = $thisActivityBargainInitiate;
            $result['express_company']    = $express->name;
            if($thisGoods->is_free_shipping == 1){
                $result['express_fee']    = 0;
            }else{
                $result['express_fee']    = $express->fee;
            }
            $result['goods_total_amount'] = $goodsTotalAmount;

        }elseif($type == 'group'){
            /** @var ActivityGroup $thisActivityGroup */
            $thisActivityGroup = ActivityGroup::whereId($activityId)->whereStatus(1)->first();
            if(!$thisActivityGroup)
                return response()->json(['level' => 'error','message' => '该拼团活动已下架！']);

            if(strtotime($thisActivityGroup->end_time) <= time())
                return response()->json(['level' => 'error','message' => '该拼团活动已结束']);

            /** @var Goods $thisGoods */
            $thisGoods = Goods::whereId($thisActivityGroup->goods_id)->whereIsShop(1)->first();
            if(!$thisGoods)
                return response()->json(['level' => 'error','message' => '该拼团商品已下架']);

            //ToDo 商品属性规格
            /** @var GoodSpu $goodSpu */
            $goodSpu = GoodSpu::whereId($goodsSpuId)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
            if (!$goodSpu)
                return response()->json(['level' => 'error','message' => '该属性的拼团商品已下架']);

            $thisGoods->goods_spu_info = $goodSpu;

            $goodsPrice = 0.00;
            if(!is_null($groupType) && $groupType != '') {
                if ($groupType == 'alone') {
                    //TODO 正常价
                    $goodsPrice = $goodSpu->price;
                } elseif ($groupType == 'initiate') {
                    //TODO 拼团价
                    /** @var ActivityGroupPrice $activityGroupPrice */
                    $activityGroupPrice = ActivityGroupPrice::whereActivityGroupId($thisActivityGroup->id)->whereGoodsId($thisGoods->id)->whereGoodsSpuId($goodSpu->id)->first();
                    if ($activityGroupPrice) {
                        $goodsPrice = $activityGroupPrice->many_price;
                    } else {
                        $goodsPrice = $goodSpu->price;
                    }
                } elseif ($groupType == 'part') {
                    //TODO 拼团价
                    /** @var ActivityGroupPrice $activityGroupPrice */
                    $activityGroupPrice = ActivityGroupPrice::whereActivityGroupId($thisActivityGroup->id)->whereGoodsId($thisGoods->id)->whereGoodsSpuId($goodSpu->id)->first();
                    if ($activityGroupPrice) {
                        $goodsPrice = $activityGroupPrice->many_price;
                    } else {
                        $goodsPrice = $goodSpu->price;
                    }

                    /** @var ActivityGroupAdd $activityGroupAdd */
                    $activityGroupAdd = ActivityGroupAdd::whereId($groupId)->first();
                    if (!$activityGroupAdd)
                        return response()->json(['level' => 'error', 'message' => '该拼团不存在']);

                    if($thisActivityGroup->max_group_num <= $activityGroupAdd->group_num)
                        return response()->json(['level' => 'error','message' => '抱歉，拼团人数已满']);

                    if (strtotime($activityGroupAdd->end_time) <= time())
                        return response()->json(['level' => 'error','message' => '该拼团已过期']);

                    if($activityGroupAdd->status != 0)
                        return response()->json(['level' => 'error','message' => '该拼团已完成']);
                } else {
                    return response()->json(['level' => 'error', 'message' => '系统错误']);
                }
            }

            //ToDo 库存
            if( $goodSpu->stock < $num)
                return response()->json(['level' => 'error','message' => '商品库存不足']);

            /** @var Express $express */
            $express = Express::whereIsDefault(1)->first();
            if(!$express)
                return response()->json(['level' => 'error','message' => '未找到快递公司']);

            if($thisGoods->is_free_shipping == 1){
                $goodsTotalAmount = round((float)$goodsPrice * (int)$num,2);
            }else{
                $goodsTotalAmount = round((float)$goodsPrice * (int)$num + (float)$express->fee,2);
            }

            $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
            $thisGoods->goods_num = $num;

            $result['goods_info']         = [$thisGoods];
            $result['activity_info']      = $thisActivityGroup;
            $result['group_type']         = $groupType;
            $result['group_id']           = $groupId;
            $result['express_company']    = $express->name;
            if($thisGoods->is_free_shipping == 1){
                $result['express_fee']    = 0;
            }else{
                $result['express_fee']    = $express->fee;
            }
            $result['goods_total_amount'] = $goodsTotalAmount;
        }else{
            return response()->json(['level' => 'error','message' => '订单类型不正确']);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $result]);
    }

    public function confirmReceipt(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $orderNum = $request->get('order_num');

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereOrderNum($orderNum)->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在！']);

        if($thisOrder->status != 3)
            return response()->json(['level' => 'error','message' => '订单状态不正确']);

        /** @var UserInfo $thisUserInfo */
        $thisUserInfo = UserInfo::whereUserId($thisOrder->user_id)->first();
        if(!$thisUserInfo)
            return response()->json(['level' => 'error','message' => '用户信息不存在']);

        /** @var OrderItem $thisOrderItem */
        $thisOrderItems = OrderItem::whereOrderId($thisOrder->id)->get();
        if(count($thisOrderItems) > 0){
            foreach($thisOrderItems as $thisOrderItem){
                /** @var GoodsSnapshot $thisGoodsSnapshot */
                $thisGoodsSnapshot = GoodsSnapshot::whereId($thisOrderItem->goods_snapshot_id)->first();
                if($thisGoodsSnapshot && ($thisGoodsSnapshot->type == 'common' || $thisGoodsSnapshot->type == 'bargain' || $thisGoodsSnapshot->type == 'group')){
                    $addIntegral = (int)$thisUserInfo->integral + ((int)$thisGoodsSnapshot->integral * (int)$thisOrderItem->num);
                    $thisUserInfo->integral = $addIntegral;
                    $thisUserInfo->save();

                    $newUserIntegralRecord = new UserIntegralRecord();
                    $newUserIntegralRecord->user_id           = $thisOrder->user_id;
                    $newUserIntegralRecord->order_num         = $thisOrder->order_num;
                    $newUserIntegralRecord->goods_id          = $thisGoodsSnapshot->id;
                    $newUserIntegralRecord->goods_name        = $thisGoodsSnapshot->name;
                    $newUserIntegralRecord->num               = $thisOrderItem->num;
                    $newUserIntegralRecord->integral          = (int)$thisGoodsSnapshot->integral * (int)$thisOrderItem->num;
                    if($thisGoodsSnapshot->type == 'common'){
                        $newUserIntegralRecord->type              = 'common';
                    }elseif($thisGoodsSnapshot->type == 'bargain'){
                        $newUserIntegralRecord->type              = 'bargain';
                    }elseif($thisGoodsSnapshot->type == 'group'){
                        $newUserIntegralRecord->type              = 'group';
                    }
                    $newUserIntegralRecord->save();
                }
            }
        }

        $thisOrder->status = 4;
        $thisOrder->save();

        return response()->json(['level' => 'success','message' => '成功收货','data' => $thisOrder]);
    }
}
